package com.kitty.cross.core.codec;

import com.kitty.mina.codec.CodecContext;
import com.kitty.mina.codec.IMessageEncoder;
import com.kitty.mina.codec.SerializerHelper;
import com.kitty.mina.message.Message;
import com.kitty.mina.session.SessionProperties;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class CrossMessageEncoder  implements ProtocolEncoder {

    @Override
    public void dispose(IoSession arg0) throws Exception {

    }

    @Override
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
        CodecContext context = (CodecContext) session.getAttribute(SessionProperties.CODEC_CONTEXT);
        if (context == null) {
            context = new CodecContext();
            session.setAttribute(SessionProperties.CODEC_CONTEXT, context);
        }
        IoBuffer buffer = writeMessage((Message) message);
        out.write(buffer);
    }

    private IoBuffer writeMessage(Message message) {
        // ----------------消息协议格式-------------------------
        // packetLength | moduleId | cmd  | body
        // int             short     byte  byte[]

        IoBuffer buffer = IoBuffer.allocate(1024);
        buffer.setAutoExpand(true);

        // 写入具体消息的内容
        IMessageEncoder msgEncoder = SerializerHelper.getInstance().getEncoder();
        byte[] body = msgEncoder.writeMessageBody(message);
        // 消息元信息常量3表示消息body前面的两个字段，一个short表示module，一个byte表示cmd,
        final int metaSize = 3;
        // 消息内容长度
        buffer.putInt(body.length + metaSize);
        int moduleId = message.getModule();
        // 写入module类型
        buffer.putInt(moduleId);

        buffer.put(body);
//		// 回到buff字节数组头部
        buffer.flip();

        return buffer;
    }

}